<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <!-- 适配手机屏幕 -->
  <meta name="viewport"
        content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" />
  <title>二维码扫码</title>

  <!-- 页面样式：深色背景+圆角按钮 -->
  <style>
    *{box-sizing:border-box}body{margin:0;background:#111;color:#fff;font:16px/1.5 sans-serif;text-align:center}
    h2{margin:1rem 0 .5rem}
    #reader{width:100%;max-width:420px;margin:0 auto}
    #result{margin-top:1rem;padding:0 .5rem;word-break:break-all}
    button{border:0;border-radius:8px;padding:.7rem 1.4rem;font-size:1rem;cursor:pointer}
    #torchBtn{background:#0a84ff;color:#fff;margin-top:1rem}
  </style>

  <!-- html5-qrcode CDN（自动选择最佳后端，含闪光灯/对焦能力检测） -->
  <script src="https://cdn.jsdelivr.net/npm/html5-qrcode@2.4.6/minified/html5-qrcode.min.js"></script>
</head>

<body>
  <h2>扫一扫</h2>
  <div id="reader"></div>
  <div id="result">等待扫码…</div>
  <button id="torchBtn" hidden>打开闪光灯</button>

<script>
  // 初始化
  const html5Qr = new Html5Qrcode("reader");
  const scanConfig = {
    fps: 15,                         // 每秒扫描帧数（越高越流畅，但耗电）
    qrbox: { width: 250, height: 250 }, // 仅取中央区域加速识别
    rememberLastUsedCamera: true,
    // 让部分浏览器走系统 BarCodeDetector，准确率更高
    experimentalFeatures: { useBarCodeDetectorIfSupported: true }
  };

  let videoTrack = null;  // 当前摄像头 track，用于控制闪光灯
  let torchOn   = false;  // 闪光灯状态

  // 切换闪光灯
  async function toggleTorch() {
    if (!videoTrack) return;
    const cap = videoTrack.getCapabilities();
    if (!cap.torch) {
      alert("当前设备不支持闪光灯控制");
      return;
    }
    torchOn = !torchOn;
    await videoTrack.applyConstraints({ advanced: [{ torch: torchOn }] });
    document.getElementById("torchBtn").textContent = torchOn ? "关闭闪光灯" : "打开闪光灯";
  }

  // 扫码成功回调
  function onScanSuccess(decodedText) {
    html5Qr.pause();                      // 暂停扫描，避免重复触发
    document.getElementById("result").textContent = "识别结果: " + decodedText;

    // 3 秒后继续扫描（可按需去掉）
    setTimeout(() => html5Qr.resume(), 3000);
  }

  // 选用后置摄像头优先
  Html5Qrcode.getCameras().then(cams => {
    if (!cams.length) throw "未检测到摄像头";

    const camId = cams[cams.length - 1].id; // 通常最后一个是后置
    html5Qr.start(camId, scanConfig, onScanSuccess).then(() => {
      // 若设备支持闪光灯，暴露按钮
      videoTrack = html5Qr.getRunningTrack();
      if (videoTrack?.getCapabilities?.().torch) {
        const btn = document.getElementById("torchBtn");
        btn.hidden = false;
        btn.addEventListener("click", toggleTorch);
      }
    });
  }).catch(err => {
    document.getElementById("result").textContent = "启动失败: " + err;
  });
</script>
</body>
</html>
